/**
 * 游戏服务层
 */
const gameDao = require('../dao/gameDao');
const { validatePagination, validateEnum } = require('../utils/validation');

/**
 * 获取游戏列表服务
 * @param {Object} query - 查询参数
 * @returns {Object} 游戏列表分页结果
 */
const getGames = async (query) => {
  const { page, limit } = validatePagination(query);
  const { category, difficulty } = query;

  // 验证难度参数
  if (difficulty) {
    const difficultyValidation = validateEnum(difficulty, ['easy', 'medium', 'hard'], '难度');
    if (!difficultyValidation.isValid) {
      throw new Error(difficultyValidation.message);
    }
  }

  const options = {
    page,
    limit,
    category,
    difficulty,
    is_active: true
  };

  const result = await gameDao.getGames(options);

  const formattedList = result.games.map(game => ({
    id: game.id,
    title: game.title,
    description: game.description,
    cover: game.cover,
    category: game.category,
    difficulty: game.difficulty,
    playCount: game.play_count || 0,
    averageScore: parseFloat(game.average_score || 0),
    duration: game.duration || 0,
    rules: game.rules,
    tags: game.tags || [],
    createdAt: game.created_at
  }));

  return {
    list: formattedList,
    total: result.total,
    page,
    limit
  };
};

/**
 * 获取游戏详情服务
 * @param {number} gameId - 游戏ID
 * @returns {Object} 游戏详情
 */
const getGameDetail = async (gameId) => {
  const game = await gameDao.getGameById(gameId);
  if (!game) {
    throw new Error('游戏不存在');
  }

  return {
    id: game.id,
    title: game.title,
    description: game.description,
    cover: game.cover,
    category: game.category,
    difficulty: game.difficulty,
    playCount: game.play_count || 0,
    averageScore: parseFloat(game.average_score || 0),
    duration: game.duration || 0,
    rules: game.rules,
    content: game.content,
    tags: game.tags || [],
    createdAt: game.created_at
  };
};

/**
 * 开始游戏服务
 * @param {number} userId - 用户ID
 * @param {number} gameId - 游戏ID
 * @returns {Object} 游戏会话信息
 */
const startGame = async (userId, gameId) => {
  // 检查游戏是否存在
  const game = await gameDao.getGameById(gameId);
  if (!game) {
    throw new Error('游戏不存在');
  }

  // 创建游戏会话
  const gameSession = await gameDao.createGameSession({
    user_id: userId,
    game_id: gameId,
    status: 'playing',
    score: 0,
    start_time: new Date()
  });

  return {
    sessionId: gameSession.id,
    gameId: gameId,
    gameTitle: game.title,
    difficulty: game.difficulty,
    duration: game.duration,
    rules: game.rules,
    content: game.content,
    startTime: gameSession.start_time
  };
};

/**
 * 提交游戏结果服务
 * @param {number} userId - 用户ID
 * @param {number} sessionId - 游戏会话ID
 * @param {Object} resultData - 游戏结果数据
 * @returns {Object} 游戏结果
 */
const submitGameResult = async (userId, sessionId, resultData) => {
  const { score, answers, playTime } = resultData;

  // 检查游戏会话是否存在
  const session = await gameDao.getGameSessionById(sessionId);
  if (!session) {
    throw new Error('游戏会话不存在');
  }

  if (session.user_id !== userId) {
    throw new Error('无权访问该游戏会话');
  }

  if (session.status !== 'playing') {
    throw new Error('游戏会话已结束');
  }

  // 更新游戏会话
  const updatedSession = await gameDao.updateGameSession(sessionId, {
    status: 'completed',
    score: score,
    answers: answers,
    play_time: playTime,
    end_time: new Date()
  });

  // 更新游戏统计
  await gameDao.updateGameStats(session.game_id, score);

  // 更新用户游戏统计
  await gameDao.updateUserGameStats(userId, session.game_id, score);

  return {
    sessionId: sessionId,
    score: score,
    playTime: playTime,
    rank: await calculateUserRank(userId, session.game_id, score),
    achievements: await checkAchievements(userId, session.game_id, score)
  };
};

/**
 * 获取游戏历史记录服务
 * @param {number} userId - 用户ID
 * @param {Object} query - 查询参数
 * @returns {Object} 游戏历史分页结果
 */
const getGameHistory = async (userId, query) => {
  const { page, limit } = validatePagination(query);
  const { gameId, startDate, endDate } = query;

  const options = {
    user_id: userId,
    game_id: gameId,
    start_date: startDate,
    end_date: endDate,
    page,
    limit
  };

  const result = await gameDao.getUserGameSessions(options);

  const formattedList = result.sessions.map(session => ({
    id: session.id,
    gameId: session.game_id,
    gameTitle: session.game ? session.game.title : '',
    score: session.score,
    playTime: session.play_time,
    status: session.status,
    startTime: session.start_time,
    endTime: session.end_time,
    createdAt: session.created_at
  }));

  return {
    list: formattedList,
    total: result.total,
    page,
    limit
  };
};

/**
 * 获取游戏排行榜服务
 * @param {number} gameId - 游戏ID
 * @param {Object} query - 查询参数
 * @returns {Object} 排行榜数据
 */
const getGameLeaderboard = async (gameId, query) => {
  const { period = 'all', page, limit } = query;
  const { page: validPage, limit: validLimit } = validatePagination({ page, limit });

  // 验证时间周期
  const periodValidation = validateEnum(period, ['day', 'week', 'month', 'all'], '时间周期');
  if (!periodValidation.isValid) {
    throw new Error(periodValidation.message);
  }

  const result = await gameDao.getGameLeaderboard(gameId, {
    period,
    page: validPage,
    limit: validLimit
  });

  const formattedList = result.rankings.map((ranking, index) => ({
    rank: (validPage - 1) * validLimit + index + 1,
    userId: ranking.user_id,
    username: ranking.user ? ranking.user.username : '',
    nickname: ranking.user ? ranking.user.nickname : '',
    avatar: ranking.user ? ranking.user.avatar : '',
    bestScore: ranking.best_score,
    averageScore: ranking.average_score,
    playCount: ranking.play_count,
    lastPlayTime: ranking.last_play_time
  }));

  return {
    list: formattedList,
    total: result.total,
    page: validPage,
    limit: validLimit
  };
};

/**
 * 获取用户游戏统计服务
 * @param {number} userId - 用户ID
 * @returns {Object} 用户游戏统计
 */
const getUserGameStats = async (userId) => {
  const stats = await gameDao.getUserGameStatistics(userId);

  return {
    totalGames: stats.total_games || 0,
    totalPlayTime: stats.total_play_time || 0,
    averageScore: parseFloat(stats.average_score || 0),
    bestScore: stats.best_score || 0,
    gamesPlayed: stats.games_played || 0,
    achievements: stats.achievements || []
  };
};

/**
 * 计算用户排名（辅助函数）
 * @param {number} userId - 用户ID
 * @param {number} gameId - 游戏ID
 * @param {number} score - 分数
 * @returns {number} 排名
 */
const calculateUserRank = async (userId, gameId, score) => {
  const rank = await gameDao.getUserRankInGame(userId, gameId, score);
  return rank || 0;
};

/**
 * 检查成就（辅助函数）
 * @param {number} userId - 用户ID
 * @param {number} gameId - 游戏ID
 * @param {number} score - 分数
 * @returns {Array} 获得的成就列表
 */
const checkAchievements = async (userId, gameId, score) => {
  // 这里可以实现成就检查逻辑
  // 例如：首次游戏、高分成就、连续游戏等
  const achievements = [];

  // 示例成就检查
  if (score >= 90) {
    achievements.push({
      id: 'high_score',
      name: '高分达人',
      description: '单次游戏得分达到90分以上'
    });
  }

  return achievements;
};

module.exports = {
  getGames,
  getGameDetail,
  startGame,
  submitGameResult,
  getGameHistory,
  getGameLeaderboard,
  getUserGameStats
};
